package com.freak.kotlinfitnessserver.queue

import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGattCharacteristic
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.os.Message
import com.freak.kotlinfitnessserver.util.ByteUtil
import com.freak.kotlinfitnessserver.util.LogUtil
import java.util.LinkedList

class BlueMessageQueue {
    companion object {
        const val TAG: String = "BlueMessageQueue"
        const val NOTIFY_MESSAGE = 1

        // 间隔100ms发送一个notify消息
        private const val MESSAGE_DELAY_TIME: Long = 100L
    }

    private var mHandlerThread: HandlerThread = HandlerThread(TAG)

    private var mBlueMessageQueueHandler: BlueMessageQueueHandler

    private val mMessageQueue: LinkedList<NotifyMessageData> = LinkedList<NotifyMessageData>()
    private var mBlueMessageQueueListen: IBlueMessageQueueListen? = null

    init {
        mHandlerThread.start()
        mBlueMessageQueueHandler = BlueMessageQueueHandler(mHandlerThread.looper)
    }

    private inner class BlueMessageQueueHandler(looper: Looper) : Handler(looper) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                NOTIFY_MESSAGE -> {
                    LogUtil.i(TAG, "NOTIFY_MESSAGE")
                    // 取出第一个数据并删除
                    val notifyMessageData = mMessageQueue.pollFirst()
                    mBlueMessageQueueListen ?: let {
                        LogUtil.i(TAG, "mBlueMessageQueueListen is null")
                        return
                    }
                    notifyMessageData ?: let {
                        LogUtil.i(TAG, "notifyMessageData is null")
                        return
                    }
                    notifyMessageData.mByteArray ?: let {
                        LogUtil.i(TAG, "mByteArray is null")
                        return
                    }
                    notifyMessageData.mDevice ?: let {
                        LogUtil.i(TAG, "mDevice is null")
                        return
                    }
                    notifyMessageData.mCharacteristic ?: let {
                        LogUtil.i(TAG, "mCharacteristic is null")
                        return
                    }
                    mBlueMessageQueueListen?.onNotifyNewMessage(
                        notifyMessageData.mByteArray!!,
                        notifyMessageData.mDevice!!,
                        notifyMessageData.mCharacteristic!!
                    )
                }
            }
        }
    }

    /**
     * 设置消息回调监听
     */
    fun setBlueMessageQueueListen(iBlueMessageQueueListen: IBlueMessageQueueListen) {
        mBlueMessageQueueListen = iBlueMessageQueueListen
    }

    fun addNotifyMessage(
        byteArray: ByteArray,
        device: BluetoothDevice,
        characteristic: BluetoothGattCharacteristic
    ) {
        LogUtil.i(
            TAG,
            "addNotifyMessage mMessageQueue.size = ${mMessageQueue.size} byteArray = ${
                ByteUtil.bytesToHexString(
                    byteArray
                )
            }"
        )
        val notifyMessageData = NotifyMessageData()
        notifyMessageData.mDevice = device
        notifyMessageData.mByteArray = byteArray
        notifyMessageData.mCharacteristic = characteristic
        mMessageQueue.add(notifyMessageData)
        if (mMessageQueue.size > 1) {
            return
        }
        mBlueMessageQueueHandler.sendEmptyMessageDelayed(NOTIFY_MESSAGE, MESSAGE_DELAY_TIME)
    }

    /**
     * 立即触发新消息
     */
    fun immediateTriggerNewMessage() {
        LogUtil.i(
            TAG,
            "immediateTriggerNewMessage mMessageQueue.size = ${mMessageQueue.size}"
        )
        if (mMessageQueue.size > 0) {
            mBlueMessageQueueHandler.removeMessages(NOTIFY_MESSAGE)
            mBlueMessageQueueHandler.sendEmptyMessage(NOTIFY_MESSAGE)
        }
    }

}